package com.cqw.auth.service;

import com.cqw.domain.SysUser;
import com.cqw.enums.UserStateEnum;
import com.cqw.exception.CommonException;
import com.cqw.mapper.one.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-07-15 16:52
 * @Description:
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {


    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser user = sysUserMapper.selectByName(userName);
        if (user == null) {
            log.error("登录用户：{}，不存在", userName);
            throw new CommonException("登录用户：" + userName + "不存在");
        }

        if (UserStateEnum.DISABLE.getCode().equals(user.getStatus())) {
            log.error("登录用户：{}，已被停用", userName);
            throw new CommonException("对不起，您的账号：" + userName + "已被停用");
        }

        if (UserStateEnum.DELETE.getCode().equals(user.getIsDelete())) {
            log.error("登录用户：{}，已被删除", userName);
            throw new CommonException("对不起，您的账号：" + userName + "已被删除");
        }

        if (user != null) {
            //查询权限
            List<String> auths = sysUserMapper.selectAuthByUserId(user.getUserId());
            user.setPermissions(auths);
        }
        return user;
    }
}
